<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a><cite>商品管理</cite></a>
    <a><cite>发行商品</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layadmin-search">
      <form class="layui-form" method="post" lay-filter="form_product_search">
        <script type="text/html" template>
          <div class="layui-inline">
            <div class="layui-form-label">关键字搜索</div>
            <div class="layui-input-inline">
              <input type="text" name="keyword" value="{{decodeURIComponent(layui.router().search.keyword || '')}}"
                     class="layui-input"
                     placeholder="请输入关键字">
            </div>
          </div>
          <div class="layui-inline layui-btn-group">
            <button type="submit" lay-submit class="layui-btn" lay-filter="submit_product_search">
              <i class="layui-icon layui-icon-search"></i>查询
            </button>
            <button type="submit" lay-submit class="layui-btn layui-btn-warm"
                    lay-filter="reset_product_search">
              <i class="layui-icon layui-icon-close"></i>重置
            </button>
          </div>

          <div class="layui-inline layui-btn-group">
            <button type="submit" lay-submit class="layui-btn layui-btn-info"
                    lay-filter="product_export">
              <i class="layui-icon layui-icon-close"></i>导出
            </button>
          </div>
        </script>
      </form>
    </div>
    <div class="layui-card-body">
      <div id="table_product"></div>
      <script type="text/html" id="tpl_name">
        <a class="layui-table-link" lay-href="product/detail/id={{d.id}}">
          {{# if (d.test_only) { }}
          <span class="layui-badge">测试</span>
          {{# } }}
          {{d.name}}
        </a>
      </script>
      <script type="text/html" id="tpl_store">
        {{# if (d.store) { }}
        {{d.store.name}}
        {{# } }}
      </script>
      <script type="text/html" id="tpl_status">
        {{# if (d.status.value === 'init') { }}
        <span class="layui-font-gray">{{d.status.description}}</span>
        {{# } }}
        {{# if (d.status.value === 'on_sale') { }}
        <span class="layui-font-green">{{d.status.description}}</span>
        {{# } }}
        {{# if (d.status.value === 'pause') { }}
        <span class="layui-font-gray">{{d.status.description}}</span>
        {{# } }}
      </script>
      <script type="text/html" id="tpl_tool">
        <a class="layui-btn layui-btn-xs" lay-event="more">操作<i class="layui-icon layui-icon-down"></i></a>
      </script>
    </div>
  </div>
</div>

<script>
  layui.use(['fox_table', 'dropdown'], function () {
    let $ = layui.$
      , fox_table = layui.fox_table
      , dropdown = layui.dropdown
      , admin = layui.admin
      , form = layui.form
      , view = layui.view

    let resourceUrl = 'agent-admin/products'

    // 列表查询
    fox_table.render({
      id: 'table_product'
      , url: resourceUrl
      , cols: [[
        {title: 'ID', field: 'id', width: 80, align: "center", sort: true}
        , {title: '商品名称', templet: '#tpl_name', minWidth: 150}
        , {title: '所属门店', templet: '#tpl_store', width: 150}
        , {title: '排序', field: 'sequence', width: 80, align: "center"}
        , {title: '发售库存', field: 'left_count', width: 100}
        , {title: '可用库存', field: 'available_tokens_count', width: 100}
        , {title: '销售量', field: 'sales_count', width: 80}
        , {title: '状态', templet: '#tpl_status', width: 80}
        , {title: '添加时间', field: 'created_at', width: 180, align: "center"}
        , {title: '操作', width: 100, align: 'left', fixed: 'right', toolbar: '#tpl_tool'}
      ]]
    });


    //加载商品类别
    let categories = [];
    admin.get('agent-admin/product_categories', function (res) {
      categories = res.data;
      form.render()
    })

    //加载商品类别
    let rightsEntities = [];
    admin.get('agent-admin/rights_entities?limit=1000', function (res) {
      rightsEntities = res.data;
      form.render()
    })

    //监听操作栏
    fox_table.toolbar(function (obj) {
      let data = obj.data;
      if (obj.event === 'more') {
        //更多下拉菜单
        let options = [{
          title: '商品信息编辑',
          id: 'product_edit'
        }, {
          title: '转售/转赠设置',
          id: 'resale_config'
        }, {
          title: '权益设置',
          id: 'rights_config'
        }, {
          title: '持有信息导出',
          id: 'buyer_export'
        }, {
          title: '提前购设置',
          id: 'early_buy'
        }];
        if (data.status.value === 'on_sale') {
          options.push({
            title: '下架',
            id: 'offline',
          })
        } else {
          options.push({
            title: '交易所',
            id: 'exchange'
          }, {
            title: data.status.value === 'init' ? '上架' : '重新上架',
            id: 'online',
          })
        }
        dropdown.render({
          elem: this
          , show: true //外部事件触发即显示
          , data: options
          , click: function (opt, othis) {
            //根据 id 做出不同操作
            if (opt.id === 'offline') {
              layer.confirm('确定下架该产品?', function (index) {
                admin.post(resourceUrl + '/' + data.id + '/offline', {}, function (res) {
                  layer.close(index);
                  fox_table.reload(); //重载表格
                })
              });
            } else if (opt.id === 'online') {
              showOnlineForm(data)
            } else if (opt.id === 'product_edit') {
              showEditForm(data)
            } else if (opt.id === 'resale_config') {
              showResaleForm(data)
            } else if (opt.id === 'early_buy') {
              showEarlyBuyList(data)
            } else if (opt.id === 'buyer_export') {
              showExportWindow(data)
            } else if (opt.id === 'rights_config') {
              showAssetForm(data);
            } else if (opt.id === 'exchange') {
              showExchangeForm(data);
            } else {
              layer.msg('开发中，敬请期待');
            }
          }
          , align: 'right' //右对齐弹出（v2.6.8 新增）
          , style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
        });
      }
    });

    //搜索
    form.on('submit(submit_product_search)', function (d) {
      fox_table.reload(d.field);
      return false;
    });
    //重置
    form.on('submit(reset_product_search)', function (d) {
      $("input[name='keyword']").val('');
      fox_table.reload({});
      return false;
    });


    form.on('submit(product_export)', function (data) {
      layer.load();
      admin.post('agent-admin/export/products', data.field, function (res) {
        layer.confirm('数据下载中，请到下载中心查看下载任务进度.', function (index) {
          layer.close(index);
          location.hash = '/ops/download';
          return false;
        });
        layer.closeAll('loading');
      }, {hasLoading: true})

      return false;
    });

    // 上架/下架
    function showOnlineForm(data) {
      let minWidth = '800px';
      let minHeight = '450px';
      admin.popup({
        title: '商品发布'
        , area: [minWidth, minHeight]
        , id: 'popup_product_online'
        , success: function (layero, index) {
          view(this.id).render('/product/online_form', data).done(function () {
            form.on('submit(submit_online)', function (d) {
              let field = d.field;
              field.show_left_count = field.show_left_count === 'on' ? 1 : 0;
              admin.post(resourceUrl + '/' + data.id + '/release', field, function (res) {
                layer.close(index);
                fox_table.reload();
              })
            })
          })
        }
      })
    }

    //编辑
    function showEditForm(data) {
      let minWidth = '800px';
      let minHeight = '1000px';
      data.categories = categories
      admin.popup({
        title: '商品信息编辑'
        , area: [minWidth, minHeight]
        , id: 'popup_product_edit'
        , success: function (layero, index) {
          view(this.id).render('/product/edit', data).done(function () {
            form.on('submit(submit_edit)', function (d) {
              let field = d.field;
              admin.post(resourceUrl + '/' + data.id + '/edit', field, function (res) {
                layer.close(index);
                fox_table.reload();
              })
            })
          })
        }
      })
    }

    //权益配置
    function showAssetForm(data) {
      let minWidth = '500px';
      let minHeight = '380px';
      data.rightsEntities = rightsEntities
      admin.popup({
        title: '权益设置'
        , area: [minWidth, minHeight]
        , id: 'popup_resale_config'
        , success: function (layero, index) {
          view(this.id).render('/product/asset_key_config', data).done(function () {
            form.on('submit(submit_resale)', function (d) {
              if (d.field.rights_type == 'entity' && !d.field.entity_id) {
                layer.msg('请选择实物权益')
                return
              }
              console.log(d.field)
              admin.post(resourceUrl + '/' + data.id + '/asset_key_set', {
                rights_type: d.field.rights_type,
                entity_id: d.field.entity_id
              }, function (res) {
                layer.close(index);
                fox_table.reload();
              })
            })
          })
        }
      })
    }

    //转售配置
    function showResaleForm(data) {
      let minWidth = '600px';
      let minHeight = '600px';
      admin.popup({
        title: '转售/转赠设置'
        , area: [minWidth, minHeight]
        , id: 'popup_resale_config'
        , success: function (layero, index) {
          view(this.id).render('/product/resale_config', data).done(function () {
            form.on('submit(submit_resale)', function (d) {
              if (d.field.resale_duration < 0) {
                layer.msg('转售冷却期不能小于0')
                return
              }
              if (d.field.give_duration < 0) {
                layer.msg('转赠冷却期不能小于0')
                return
              }
              console.log(d.field)
              admin.post(resourceUrl + '/' + data.id + '/resale_config', {
                resale_forbid: d.field.can_resale === 'on' ? 0 : 1,
                resale_duration: d.field.resale_duration,
                resale_max_price: d.field.resale_max_price,
                resale_price_incr_limit: d.field.resale_price_incr_limit,
                resale_price_decr_limit: d.field.resale_price_decr_limit,
                resale_init_base_price: d.field.resale_init_base_price,
                give_forbid: d.field.can_give === 'on' ? 0 : 1,
                give_duration: d.field.give_duration
              }, function (res) {
                layer.close(index);
                fox_table.reload();
              })
            })
          })
        }
      })
    }

    //提前购设置
    function showEarlyBuyList(data) {
      let minWidth = '800px';
      let minHeight = '880px';
      admin.popup({
        title: '提前购用户清单'
        , area: [minWidth, minHeight]
        , id: 'popup_early_buy'
        , success: function (layero, index) {
          view(this.id).render('/product/early_buy', data).done(function () {
          })
        }
      })
    }

    //导出
    function showExportWindow(data) {
      let minWidth = '600px';
      let minHeight = '220px';
      admin.popup({
        title: '持有人导出'
        , area: [minWidth, minHeight]
        , id: 'popup_export'
        , success: function (layero, index) {
          view(this.id).render('/product/export', data).done(function () {
          })
        }
      })
    }

    //交易所设置
    function showExchangeForm(data) {
      let minWidth = '600px';
      let minHeight = '500px';
      admin.popup({
        title: '交易所设置'
        , area: [minWidth, minHeight]
        , id: 'popup_exchange'
        , success: function (layero, index) {
          view(this.id).render('/product/exchange', data).done(function () {
            form.on('submit(submit_resale)', function (d) {
              admin.post(resourceUrl + '/' + data.id + '/exchange_config', {
                is_locked: d.field.is_locked === 'on' ? 1 : 0,
                exchange_channel: d.field.exchange_channel
              }, function (res) {
                layer.close(index);
                fox_table.reload();
              })
            })
          })
        }
      })
    }
  })
</script>

